package com.nifostasky.service.impl;

import com.nifostasky.entity.SysMenu;
import com.nifostasky.entity.SysUser;
import com.nifostasky.entity.SysUserToken;
import com.nifostasky.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ShiroServiceImpl implements ShiroService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList = null;
        //系统管理员,用户最高权限
        if (userId == 1){
            //获取权限表中已有的所有权限
            List<SysMenu> menuList = sysMenuService.list();
            permsList = new ArrayList<>(menuList.size());
            for(SysMenu menu : menuList){
                permsList.add(menu.getPerms());
            }
        }else{
            List<SysMenu> sysMenus = sysUserService.queryAllPerms(userId);
            permsList = sysMenus.stream().map(i -> i.getPerms()).collect(Collectors.toList());
        }
        //处理获取的权限集合, 整理为用户权限列表
        Set<String> permsSet = new HashSet<>();
        permsList.stream().forEach(i -> {
            //权限不为空时,添加到用户权限列表中
            if (StringUtils.isNotBlank(i)){
                String[] split = i.trim().split(",");
                permsSet.addAll(Arrays.asList(split));
            }
        });
        return permsSet;
    }

    @Override
    public SysUserToken queryByToken(String token) {
        return null;
    }

    @Override
    public SysUser queryUser(Long userId) {
        return sysUserService.getById(userId);
    }
}
